<?php

class sitemap extends Front {

    public function version() {
        return array(
            'version' => '1.0',
            'pid' => 'sitemap',
            'description' => '生成百度谷歌sitemap xml文件以及网站地图',
            'home' => 'http://blog.com',
            'author' => '幽灵传说',
            'config' => 1,
            'status' => 1
        );
    }

    public function copy() {
        if ( ( $content = $this->get_config() ) && $content[ 'add_footer' ] ) {
            echo<<<EOT
<a href="{$this->obj->setting[ 'weburl' ]}/sitemap.html">网站地图</a> <a href="{$this->obj->setting[ 'weburl' ]}/sitemap.xml">SiteMap</a>

EOT;
        }
    }

    // 发布or更新文章自动生成xml
    public function add_post() {
        $content = $this->get_config();
        if ( !$content ) {
            return;
        }

        if ( $content[ 'auto_sitemap' ] ) {

            $this->build_xml( $content );

            if ( $content[ 'sitemap_html' ] ) {
                $this->build_html( $content );
            }
        }
    }

    // 获取插件配置信息
    private function get_config() {
        $config = APP_PLUGIN . "sitemap/sitemap_config.php";
        if ( is_file( $config ) ) {
            $content = file_get_contents( $config );
            $content = unserialize( substr( $content, 14 ) );
            return $content;
        }
        return false;
    }


    // 生成XML与HTML地图
    public function run() {
        $content = $this->get_config();
        if ( !$content ) {
            return;
        }

        if ( !is_writable_dir( APP_PATH . "/" ) ) {
            exit( 'sitemap 目录' . APP_PATH . '/不可写!' );
        }

        echo $this->build_xml( $content );

        if ( $content[ 'sitemap_html' ] ) {
            $this->build_html( $content );
        }
    }

    // 生成sitemap xml
    private function build_xml( $args ) {
        $xmlFile = APP_PATH . "/{$args[ 'sitemap_name' ]}";
        $xml = '<?xml version="1.0" encoding="UTF-8"?><?xml-stylesheet type="text/xsl" href="' . $this->setting[ 'weburl' ] . '/system/plugin/sitemap/sitemap.xsl"?>';
        $xml .= '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">';
        $xml .= $this->get_index_xml( $args );
        $xml .= $this->get_post_xml( $args );
        $xml .= $this->get_sort_xml( $args );
        $xml .= '</urlset>';

        file_put_contents( $xmlFile, $xml );
        chmod( $xmlFile, 0666 );
        return 'success';
    }

    // 返回首页xml
    private function get_index_xml( $args ) {
        $index_url = $this->setting[ 'weburl' ];
        return $this->xml_code( $index_url, time(), $args[ 'index_changefreq' ], $args[ 'index_priority' ] );
    }

    // 返回文章xml
    private function get_post_xml( $args ) {
        $xml_post = '';
        $sql = "SELECT id, title, model, alias, dateline, lastdate
                FROM  `{$this->model->t('article')}` AS a
                LEFT JOIN (
                    SELECT aid, MAX( dateline ) AS lastdate
                    FROM  `{$this->model->t('comment')}`
                    GROUP BY aid
                ) AS c ON ( a.id = c.aid )
                WHERE a.model <> 'link'
                AND a.isHide = 0
                ORDER BY id DESC
                LIMIT {$args[ 'max_post' ]}";
        $result = $this->model->findSql( $sql );

        foreach ( $result as $v ) {
            $url = $this->archives_url( $v );
            $model = $v[ 'model' ] == 'article' ? 'post' : 'page';
            $date = $v[ 'lastdate' ] ? $v[ 'lastdate' ] : $v[ 'dateline' ];
            $xml_post .= $this->xml_code( $url, $date, $args[ $model . '_changefreq' ], $args[ $model . '_priority' ] );
        }
        return $xml_post;
    }

    // 返回分类xml
    private function get_sort_xml( $args ) {
        $xml_sort = '';
        $sort = $this->sort();
        foreach ( $sort as $v ) {
            $url = $this->sort_url( $v );
            $xml_sort .= $this->xml_code( $url, time(), $args[ 'sort_changefreq' ], $args[ 'sort_priority' ] );
        }
        return $xml_sort;
    }

    private function xml_code( $url, $lastmod, $changefreq, $priority ) {
        $url = htmlspecialchars( $url );
        $lastmod = gmdate( 'c', $lastmod );
        return "<url>\n<loc>$url</loc>\n<lastmod>$lastmod</lastmod>\n<changefreq>$changefreq</changefreq>\n<priority>$priority</priority>\n</url>\n";
    }

    // 生成网站地图
    private function build_html( $args ) {
        $post = $sort = $page = "";

        $this->model->table = "article";
        $result = $this->model->findAll( array( 'model' => 'article' ), null, null, $args[ 'max_post' ] );
        foreach ( $result as $v ) {
            $url = $this->archives_url( $v );
            $post .= "<li><a href=\"{$url}\" title=\"{$v['title']}\">{$v['title']}</a></li>";
        }

        $page_result = $this->model->Node()->dataTree( $this->model->Cache()->get( 'page' ) );
        $page = $this->Node()->dataTreeLiUl( $page_result, 'archives' );

        $sort_result = $this->sort( 'article', 0, 'dataTree' );
        $sort = $this->Node()->dataTreeLiUl( $sort_result );

        $html = file_get_contents( APP_PLUGIN . "sitemap/sitemap.html" );
        $html = str_replace( array( "{weburl}", "{webname}" ), array( $this->setting[ 'weburl' ], $this->setting[ 'webname' ] ), $html );
        $html = str_replace( array( "{post}", "{sort}", "{xmlname}", "{date}" ), array( $post, $sort, $args[ 'sitemap_name' ], date( 'Y-m-d H:i:s' ) ), $html );
        $html = str_replace( array( "{page}" ), array( $page ), $html );

        $html = str_replace( array( "\n", "\r", "\t", "  " ), "", $html );
        file_put_contents( APP_PATH . "/sitemap.html", $html );
        chmod( APP_PATH . "/sitemap.html", 0666 );
    }
}